import os
from flask import Blueprint, send_from_directory
from flask import current_app, request
from shortuuid import uuid
from models.img import ImageModel
from exts import db


bp = Blueprint('images', __name__, url_prefix='/images')


# 1、获取图片
@bp.route('/<string:dir_name>/<string:file_name>', methods=['GET'])
def get_img(dir_name, file_name):
    try:
        image_dir = os.path.join(current_app.config['IMAGE_ROOT'], dir_name)
        # 返回图片
        return send_from_directory(image_dir, file_name)
    except Exception as e:
        current_app.logger.error(e)
        return str(e)


# 2、上传图片,注意：微信小程序uploadfile只接受字符串
@bp.route('/<string:dir_name>', methods=['POST'])
def upload_img(dir_name):
    img = request.files.get("img")
    print("上传文件名", img.filename)
    suffix = img.filename.rsplit('.')[-1]
    if not img or suffix not in ['jpg', 'png', 'gif', 'jpeg']:
        return ''
    img_dir = os.path.join(current_app.config['IMAGE_ROOT'], dir_name)
    # 设置img文件名
    img_name = str(uuid()) + '.' + suffix
    img_path = os.path.join(img_dir, img_name)
    # 保存图片
    img.save(img_path)
    # 生成图片链接
    img_url = current_app.config['BASE_SERVER'] + '/images/' + dir_name + '/' + img_name
    print("保存的文件url", img_url)
    # 返回图片链接,微信小程序uploadfile只接受字符串
    return img_url


# 3、文章更新时删除图片
def delete_img_update(article_id, articel_type, new_imgs, img_list):
    # 修改image库，删除未使用的图片文件
    all_imgs = ImageModel.query.filter(ImageModel.article_id == article_id, ImageModel.type == articel_type).all()
    # 遍历图片(新+旧)，如果旧图片不在新图片和未修改图片里面，则删除
    for img in all_imgs:
        if new_imgs:
            # 有新增
            if (img.url not in new_imgs) and (img.url not in img_list):
                # 删除数据库信息
                db.session.delete(img)
                # 删除文件
                delete_img_by_url(img.url)
        else:
            # 无新增
            if img.url not in img_list:
                # 删除数据库信息
                db.session.delete(img)
                # 删除文件
                delete_img_by_url(img.url)
    db.session.commit()


# 4、删除文章时删除图片
def delete_img_delete(article_id, article_type):
    imgs = ImageModel.query.filter(ImageModel.article_id == article_id, ImageModel.type == article_type).all()
    for img in imgs:
        delete_img_by_url(img.url)
        db.session.delete(img)
    db.session.commit()


# 图片根据url删除，内部调用
def delete_img_by_url(img_url):
    dir_name = img_url.split('/')[-2]
    file_name = img_url.split('/')[-1]
    print('delete_img_by_url', dir_name, file_name)
    if file_name not in ["default.jpg", "default.jpeg", "default.png", "default.gif", ""]:
        filepath = os.path.join(current_app.config['IMAGE_ROOT'], dir_name, file_name)
        if file_delete(filepath):
            return '删除成功'
    return '该文件无需删除'


# 判断图片管理数据库中单个文件是否已存在
def file_exists(url: str) -> str:
    img = ImageModel.query.filter(ImageModel.url == url).all()
    if img:
        return img.url
    return ''


def file_delete(filepath):
    if os.path.exists(filepath):
        os.remove(filepath)
        current_app.logger.warning(f"已删除文件:{filepath}")
        return True
    else:
        print(f'待删除文件{filepath}不存在')
    return False
